package com.bootadmin.controller.system.ao.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bootadmin.controller.system.ao.RoleAO;
import com.bootadmin.controller.system.dto.request.RolePageListDTO;
import com.bootadmin.core.utils.StringUtils;
import com.bootadmin.core.web.ResultJson;
import com.bootadmin.entity.Role;
import com.bootadmin.enums.StateEnum;
import com.bootadmin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author kongzm
 * @description: RoleAOImpl
 * @date 2022/1/15 19:37
 */
@Component
public class RoleAOImpl implements RoleAO {

    @Autowired
    private RoleService roleService;

    @Override
    public ResultJson save(HttpServletRequest request, Long id, String name, String remark) {
        if (StringUtils.isEmpty(name)) {
            return ResultJson.failure("角色名称不能为空");
        }

        Role role = new Role();
        if (id == null) {
            role.setName(name);
            role.setRemark(StringUtils.nullSafe(remark));
        } else {
            Role roleData = roleService.getById(id);
            role.setVersion(roleData.getVersion());
        }

        role.setName(name);
        role.setRemark(StringUtils.nullSafe(remark));
        roleService.saveOrUpdate(role);
        return ResultJson.success("保存成功");
    }

    @Override
    public ResultJson deleteById(HttpServletRequest request, Long id) {
        Role role = roleService.getById(id);
        int state = role.getState().equals(StateEnum.ONE.getValue()) ? StateEnum.ZERO.getValue() : StateEnum.ONE.getValue();
        role.setState(state);
        roleService.updateById(role);
        return ResultJson.success();
    }

    @Override
    public ResultJson selectPageList(RolePageListDTO rolePageListDTO) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if (!StringUtils.isTrimEmpty(rolePageListDTO.getName())) {
            wrapper.like("name", rolePageListDTO.getName().trim());
        }
        wrapper.orderByDesc("id");

        Page<Role> page = new Page<>(rolePageListDTO.getPageNum(), rolePageListDTO.getPageSize());
        IPage<Role> list = roleService.page(page, wrapper);
        return ResultJson.success(list);
    }
}
